#include <stdint.h>
#include "icc.h"
#include "character_module.h"

#define		DEFAULT_FIDI			    0x11
#define		DEFAULT_T01CONVCHECKSUM	    0x00
#define		DEFAULT_GUARDTIME		    0x01
#define		DEFAULT_WAITINGINTEGER	    0x0A

#define		DEFAULT_IFSC			    0x20
#define		DEFAULT_NAD				    0x00
#define		DEFAULT_BWICWI			    0x4d

#define		START_BITS	1
#define 	DATA_BITS	8
#define		PARITY_BITS	1

#define		get_frame_duration(stop_bits) (START_BITS + DATA_BITS + PARITY_BITS + (stop_bits))

static icc_t Default_Icc = 
{
	0,				//active_flag
	DIRECT_BYTE,	//uint8_t byte_direction;
	3,		//uint8_t voltage;
	0,		//uint8_t retransmit_times;
	0,		//uint8_t protocol_type;
	0x11,	//uint8_t FiDi;
	2,		//uint8_t stop_bit;				//字节停止位个数
	12,		//uint16_t char_duration; //连续两字节起始位最小间隔时间
	0,		//uint16_t extra_guardtime;		//连续两个字节间的保护时间
	16,		//uint16_t oppositive_guardtime;	//反向两字节起始位间隔时间

	/*
	EMV4.3 Book1 8.4
	The terminal shall be able to receive an ATR having maximum interval 
	between two consecutive characters of  10,080 initial etus (9,600 + 480 initial 
	etus).
	*/
	//T = 0
	//9600 + 480,	//uint32_t WWT;	
	9600 + 480*2,	//uint32_t WWT;	
	//16,		//uint32_t opposite_guard_time; //T = 0,字节反向传输保护时间
	//T = 1
	0x00,	//multipleBWT
	11 + (1 << 4) * 960,	//uint32_t BWT;
	0x0D,	//uint32_t CWT;		
	//22,		//uint32_t BGT;	
	0x20,	//uint8_t IFSC;
	0,		// SN_out;
	0,		//SN_in
	0,		//error_countor
	0		//work mode Normal or EMV
 };


void ICC_SetWorkMode(uint8_t work_mode)
{
	Default_Icc.work_mode = work_mode;
}


void ICC_DefaultInit(icc_t *icc)
{
	/*
	icc->byte_direction = DIRECT_BYTE;
	icc->FiDi = 0x11;
	icc->protocol_type = 0;
	icc->retransmit_times = 0;
	icc->voltage = 5;
	icc->GT = 1;
	*/

	*icc = Default_Icc;
}

static void config_t1_icc(icc_t *icc)
{
	icc->stop_bit = 1;
	icc->oppositive_guardtime = 22;
	icc->retransmit_times = 0;
}

static void config_t0_icc(icc_t *icc)
{
	icc->stop_bit = 2;
	icc->oppositive_guardtime = 16;
	icc->retransmit_times = 5;
}

void ICC_Config(icc_t *icc)
{	
	if(icc->protocol_type == 1)
	{
		config_t1_icc(icc);
	}
	else
	{
		config_t0_icc(icc);
	}
}

